#!/usr/bin/env node

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 获取提交信息
const commitMsg = process.argv[2] || '';
const commitType = process.argv[3] || 'feat'; // feat, fix, docs, style, refactor, test, chore
const isRelease = process.argv[4] === 'release'; // 是否为版本发布

// 读取当前的 CHANGELOG.md
const changelogPath = path.join(__dirname, '..', 'CHANGELOG.md');
let changelogContent = fs.readFileSync(changelogPath, 'utf8');

// 获取当前日期和时间
const now = new Date();
const today = now.toISOString().split('T')[0];
const timeStr = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日${now.getHours().toString().padStart(2, '0')}时${now.getMinutes().toString().padStart(2, '0')}分${now.getSeconds().toString().padStart(2, '0')}秒`;

// 根据提交类型确定更新类型和图标
const getChangeType = (type) => {
  const typeMap = {
    'feat': { label: '🚀 新增功能', icon: '🚀' },
    'fix': { label: '🐛 修复问题', icon: '🐛' },
    'docs': { label: '📚 文档更新', icon: '📚' },
    'style': { label: '💄 代码格式', icon: '💄' },
    'refactor': { label: '♻️ 代码重构', icon: '♻️' },
    'test': { label: '🧪 测试相关', icon: '🧪' },
    'chore': { label: '🔧 构建工具', icon: '🔧' }
  };
  return typeMap[type] || { label: '📝 变更', icon: '📝' };
};

// 格式化提交信息
const formatCommitMsg = (msg) => {
  // 移除类型前缀（如 feat:, fix: 等）
  return msg.replace(/^(feat|fix|docs|style|refactor|test|chore):\s*/i, '');
};

// 移除所有"最近提交"标记
const removeLatestCommitMarks = (content) => {
  return content.replace(/\s*（最近提交）\d{4}年\d{1,2}月\d{1,2}日\d{2}时\d{2}分\d{2}秒/g, '');
};

// 添加"最近提交"标记到指定条目
const addLatestCommitMark = (content, changeTypeLabel, formattedMsg) => {
  const changeTypeIndex = content.indexOf(`### ${changeTypeLabel}`);
  if (changeTypeIndex === -1) return content;
  
  // 查找该类型下的所有条目
  const nextSection = content.indexOf('### ', changeTypeIndex + 1);
  const sectionEnd = nextSection !== -1 ? nextSection : content.length;
  const sectionContent = content.substring(changeTypeIndex, sectionEnd);
  
  // 查找包含该提交信息的行
  const linePattern = new RegExp(`- ${formattedMsg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, 'g');
  const match = linePattern.exec(sectionContent);
  
  if (match) {
    const lineStart = changeTypeIndex + match.index;
    const lineEnd = content.indexOf('\n', lineStart);
    const beforeLine = content.substring(0, lineStart);
    const afterLine = lineEnd !== -1 ? content.substring(lineEnd) : '';
    const lineContent = lineEnd !== -1 ? content.substring(lineStart, lineEnd) : content.substring(lineStart);
    
    // 添加时间标记
    const newLine = `${lineContent} （最近提交）${timeStr}`;
    return beforeLine + newLine + afterLine;
  }
  
  return content;
};

const changeType = getChangeType(commitType);
const formattedMsg = formatCommitMsg(commitMsg);

if (isRelease) {
  // 版本发布：将"未发布"部分移动到新版本
  const version = process.argv[5] || '0.1.1';
  const unreleasedStart = changelogContent.indexOf('## [未发布]');
  const unreleasedEnd = changelogContent.indexOf('## [', unreleasedStart + 1);
  
  if (unreleasedEnd === -1) {
    // 如果没有下一个版本，在文件末尾添加
    const newVersionSection = `\n## [${version}] - ${today}\n\n`;
    changelogContent = changelogContent.replace('## [未发布]', `## [${version}] - ${today}`);
  } else {
    // 在下一个版本之前插入新版本
    const unreleasedContent = changelogContent.substring(unreleasedStart, unreleasedEnd);
    const newVersionContent = unreleasedContent.replace('## [未发布]', `## [${version}] - ${today}`);
    
    const beforeUnreleased = changelogContent.substring(0, unreleasedStart);
    const afterUnreleased = changelogContent.substring(unreleasedEnd);
    
    changelogContent = beforeUnreleased + newVersionContent + '\n\n' + afterUnreleased;
  }
  
  // 重新添加空的"未发布"部分
  const unreleasedSection = `## [未发布]\n\n### 🚀 新增功能\n\n### 🐛 修复问题\n\n### 🔧 构建工具\n\n### 📚 文档更新\n\n### 🧪 测试相关\n\n---\n\n`;
  
  const firstVersionIndex = changelogContent.indexOf('## [', changelogContent.indexOf('## [未发布]') + 1);
  if (firstVersionIndex !== -1) {
    const beforeVersions = changelogContent.substring(0, firstVersionIndex);
    const afterVersions = changelogContent.substring(firstVersionIndex);
    changelogContent = beforeVersions + unreleasedSection + afterVersions;
  }
  
  console.log(`✅ 已发布版本 ${version}`);
} else {
  // 普通提交：在"未发布"部分添加新的条目
  
  // 首先移除所有现有的"最近提交"标记
  changelogContent = removeLatestCommitMarks(changelogContent);
  
  const unreleasedSection = changelogContent.indexOf('## [未发布]');
  const nextSection = changelogContent.indexOf('## [', unreleasedSection + 1);

  if (nextSection === -1) {
    // 如果没有找到下一个版本，在文件末尾添加
    const insertPosition = changelogContent.indexOf('### 🚀 新增功能', unreleasedSection);
    if (insertPosition !== -1) {
      const beforeInsert = changelogContent.substring(0, insertPosition);
      const afterInsert = changelogContent.substring(insertPosition);
      changelogContent = beforeInsert + `- ${formattedMsg} （最近提交）${timeStr}\n` + afterInsert;
    }
  } else {
    // 在下一个版本之前插入
    const beforeNextSection = changelogContent.substring(0, nextSection);
    const afterNextSection = changelogContent.substring(nextSection);
    
    // 查找"未发布"部分的合适位置
    const changeTypeIndex = beforeNextSection.indexOf(`### ${changeType.label}`, unreleasedSection);
    
    if (changeTypeIndex !== -1) {
      // 如果该类型已存在，在其后添加
      const endOfType = beforeNextSection.indexOf('\n\n', changeTypeIndex);
      const insertPosition = endOfType !== -1 ? endOfType : beforeNextSection.indexOf('\n', changeTypeIndex);
      
      const beforeInsert = beforeNextSection.substring(0, insertPosition);
      const afterInsert = beforeNextSection.substring(insertPosition);
      changelogContent = beforeInsert + `\n- ${formattedMsg} （最近提交）${timeStr}` + afterInsert + afterNextSection;
    } else {
      // 如果该类型不存在，在"未发布"部分添加新类型
      const unreleasedEnd = beforeNextSection.lastIndexOf('\n', nextSection - 1);
      const beforeInsert = beforeNextSection.substring(0, unreleasedEnd);
      const afterInsert = beforeNextSection.substring(unreleasedEnd);
      changelogContent = beforeInsert + `\n\n### ${changeType.label}\n- ${formattedMsg} （最近提交）${timeStr}` + afterInsert + afterNextSection;
    }
  }
}

// 写回文件
fs.writeFileSync(changelogPath, changelogContent, 'utf8');

if (!isRelease) {
  console.log(`✅ 已更新 CHANGELOG.md: ${changeType.icon} ${formattedMsg} （最近提交）${timeStr}`);
}
